﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Configuration;
using ASBCC.Workflow.K2Manager;
using ASBCC.Database.Entity;


namespace ASBCC.Workflow.Client
{
    public class EZVisitProcessStampControlBase : System.Web.UI.UserControl, IWorkflowControl
    {
        private string _activeActivityName;

        private string GetProcName()
        {
            IWorkflowPage workflowPage = Page as IWorkflowPage;
            if (workflowPage == null) return string.Empty;
            return workflowPage.GetProcName();
        }

        private IWorkflowController GetWorkflowController()
        {
            IWorkflowPage workflowPage = Page as IWorkflowPage;
            if (workflowPage == null) return null;
            return workflowPage.GetWorkflowController();
        }

        private string GetApplicationBasePath()
        {
            return this.ResolveUrl("~/");
            //string path = ConfigurationManager.AppSettings["ApplicationBasePath"];
            //if (path.EndsWith("/")) return path;
            //return path + "/";
        }

        private void BindControls()
        {
            Label lblActiveActivityName = GetActiveActivityNameLabel();
            if (lblActiveActivityName != null) lblActiveActivityName.Text = string.IsNullOrEmpty(_activeActivityName) ? ActivityNameConsts.Closed : _activeActivityName;
        }

        public string GetStampImage(object dataItem)
        {
            DataRowView drv = (DataRowView)dataItem;
            string actionType = Convert.ToString(drv["ActionType"]);
            string stampType = Convert.ToString(drv["StampType"]);
            if (stampType == K2StampType.Done)
            {
                if (actionType == K2ActionType.Approve)
                {
                    return string.Format("{0}Workflow/Images/{1}", GetApplicationBasePath(), "Approved.gif");
                }
                else if (actionType == K2ActionType.Review)
                {
                    return string.Format("{0}Workflow/Images/{1}", GetApplicationBasePath(), "Reviewed.gif");
                }
                else if (actionType == K2ActionType.Reject)
                {
                    return string.Format("{0}Workflow/Images/{1}", GetApplicationBasePath(), "Rejected.gif");
                }
                else if (actionType == K2ActionType.Acknowledge)
                {
                    return string.Format("{0}Workflow/Images/{1}", GetApplicationBasePath(), "Acknowledge.gif");
                }
                else if (actionType == K2ActionType.Validate)
                {
                    return string.Format("{0}Workflow/Images/{1}", GetApplicationBasePath(), "Validate.gif");
                }

                return string.Empty;
            }
            else if (stampType == K2StampType.Active)
            {
                return string.Format("{0}Workflow/Images/{1}", GetApplicationBasePath(), "Pending1.gif");
            }
            else if (stampType == K2StampType.Tobe)
            {
                return string.Format("{0}Workflow/Images/{1}", GetApplicationBasePath(), "Pending2.gif");
            }
            return string.Empty;
        }

        public string GetStampTitle(object dataItem)
        {
            return string.Empty;
        }

        public string GetStampOwner(object dataItem)
        {
            DataRowView drv = (DataRowView)dataItem;
            string owner = Convert.ToString(drv["OwnerEn"]);
            string delegateFrom = (drv["DelegateFromEn"] == null || drv["DelegateFromEn"] == DBNull.Value) ? string.Empty : drv["DelegateFromEn"].ToString();
            string stampType = Convert.ToString(drv["StampType"]);
            string activityName = Convert.ToString(drv["ActivityName"]);
            if (stampType == K2StampType.Done || stampType == K2StampType.Active)
            {
                if (string.IsNullOrEmpty(delegateFrom))
                {
                    return owner;
                }
                else
                {
                    return string.Format("{0}({1})", owner, delegateFrom);
                }
            }
            else
            {
                return activityName;
            }
        }

        public string GetStampDate(object dataItem)
        {
            DataRowView drv = (DataRowView)dataItem;
            string stampType = Convert.ToString(drv["StampType"]);
            if (stampType == K2StampType.Done)
            {
                DateTime createdDate = Convert.ToDateTime(drv["CreatedDate"]);
                return createdDate.ToString("yyyy-MM-dd");
            }
            else
            {
                return "xxxx-xx-xx";
            }
        }

        #region Virtual Members

        public virtual HtmlGenericControl GetStampControl()
        {
            return null;
        }

        public virtual Label GetActiveActivityNameLabel()
        {
            return null;
        }

        public virtual DataList GetStampDataList()
        {
            return null;
        }
        public virtual DataList GetStampDataListEZVisit()
        {
            return null;
        }
        public virtual DataList GetStampDataListPostEZVisit()
        {
            return null;
        }

        public virtual DataTable GetDataSource(int appFormId, int procInstId)
        {
            DataTable done = K2DataHelper.GetProcessStamp(procInstId);

            foreach (DataRow row in done.Rows)
            {
                row["StampType"] = K2StampType.Done;
            }

            MyActivityTableEntitySet active = K2DataHelper.GetMyActivities(procInstId, new int[] { (int)MyActivityStatus.Normal });

            string activeActivityName = string.Empty;
            string targetActivityName = string.Empty;
            if (active != null)
            {
                foreach (MyActivityTableEntity entity in active)
                {
                    if (string.IsNullOrEmpty(activeActivityName))
                    {
                        activeActivityName = entity.K2ActivityName;
                        _activeActivityName = activeActivityName;
                    }
                    else
                    {
                        activeActivityName = entity.K2ActivityName;
                        string tempActivity = ";" + _activeActivityName;
                        if (tempActivity.IndexOf(";" + activeActivityName) == -1)
                            _activeActivityName += ";" + activeActivityName;
                    }

                    if (entity.SourceActionType == K2ActionType.AskForMore)
                    {
                        if (string.IsNullOrEmpty(targetActivityName))
                        {
                            targetActivityName = entity.TargetActivityName;
                        }
                    }

                    DataRow row = done.NewRow();
                    row["ProcessStampID"] = Guid.NewGuid();
                    row["ProcName"] = GetProcName();
                    row["ActivityName"] = entity.K2ActivityName;
                    row["ActionType"] = string.Empty;
                    row["OwnerID"] = entity.OwnerID ?? 0;
                    row["OwnerEn"] = entity.OwnerEn;
                    row["OwnerCn"] = entity.OwnerCn;
                    row["DelegateFromID"] = entity.DelegateFromID ?? 0;
                    row["DelegateFromEn"] = entity.DelegateFromEn;
                    row["DelegateFromCn"] = entity.DelegateFromCn;
                    row["ApplicationNo"] = entity.ApplicationNo;
                    row["ProcInstID"] = entity.K2ProcInstID ?? 0;
                    row["CreatedDate"] = entity.CreatedDate;
                    row["Status"] = 0;
                    //row["ActionRecordID"] = ;
                    row["StampType"] = K2StampType.Active;
                    done.Rows.Add(row);
                }
            }

            if (!string.IsNullOrEmpty(targetActivityName))
            {
                _activeActivityName = activeActivityName + " asked for more";
            }

            if (!string.IsNullOrEmpty(activeActivityName))
            {
                IWorkflowController workflowController = GetWorkflowController();
                if (workflowController != null)
                {
                    ActivityLink activityLink = workflowController.GetActivityLink();
                    if (activityLink != null)
                    {
                        ActivityLinkNode foundNode = activityLink.FindNode(activeActivityName);
                        if (foundNode != null)
                        {
                            ActivityLinkNode current = foundNode.LastChild;
                            if (current != null && current.Value != ActivityNameConsts.End)
                            {
                                do
                                {
                                    DataRow row = done.NewRow();
                                    row["ProcessStampID"] = Guid.NewGuid();
                                    row["ProcName"] = GetProcName();
                                    row["ActivityName"] = current.Value;
                                    row["Status"] = 0;
                                    row["StampType"] = K2StampType.Tobe;
                                    done.Rows.Add(row);
                                    current = current.LastChild;
                                } while (current != null && current.Value != ActivityNameConsts.End);
                            }
                        }
                    }
                }
            }

            done.AcceptChanges();
            return done;
        }

        public virtual DataTable GetDataSourceEZVisit(int appFormId, int procInstId)
        {
            //DataTable done = K2DataHelper.GetProcessStamp(procInstId);
            DataTable done = K2DataHelper.GetProcessStampEZVisit(procInstId);

            foreach (DataRow row in done.Rows)
            {
                row["StampType"] = K2StampType.Done;
            }

            MyActivityTableEntitySet active = K2DataHelper.GetMyActivities(procInstId, new int[] { (int)MyActivityStatus.Normal });

            string activeActivityName = string.Empty;
            string targetActivityName = string.Empty;
            if (active != null)
            {
                foreach (MyActivityTableEntity entity in active)
                {
                    if (string.IsNullOrEmpty(activeActivityName))
                    {
                        activeActivityName = entity.K2ActivityName;
                        _activeActivityName = activeActivityName;
                    }
                    else
                    {
                        activeActivityName = entity.K2ActivityName;
                        string tempActivity = ";" + _activeActivityName;
                        if (tempActivity.IndexOf(";" + activeActivityName) == -1)
                            _activeActivityName += ";" + activeActivityName;
                    }

                    if (entity.SourceActionType == K2ActionType.AskForMore)
                    {
                        if (string.IsNullOrEmpty(targetActivityName))
                        {
                            targetActivityName = entity.TargetActivityName;
                        }
                    }
                    if (entity.K2ActivityName.IndexOf("Post") == -1)
                    {
                        DataRow row = done.NewRow();
                        row["ProcessStampID"] = Guid.NewGuid();
                        row["ProcName"] = GetProcName();
                        row["ActivityName"] = entity.K2ActivityName;
                        row["ActionType"] = string.Empty;
                        row["OwnerID"] = entity.OwnerID ?? 0;
                        row["OwnerEn"] = entity.OwnerEn;
                        row["OwnerCn"] = entity.OwnerCn;
                        row["DelegateFromID"] = entity.DelegateFromID ?? 0;
                        row["DelegateFromEn"] = entity.DelegateFromEn;
                        row["DelegateFromCn"] = entity.DelegateFromCn;
                        row["ApplicationNo"] = entity.ApplicationNo;
                        row["ProcInstID"] = entity.K2ProcInstID ?? 0;
                        row["CreatedDate"] = entity.CreatedDate;
                        row["Status"] = 0;
                        //row["ActionRecordID"] = ;
                        row["StampType"] = K2StampType.Active;
                        done.Rows.Add(row);
                    }
                }
            }

            if (!string.IsNullOrEmpty(targetActivityName))
            {
                _activeActivityName = activeActivityName + " asked for more";
            }

            if (!string.IsNullOrEmpty(activeActivityName))
            {
                IWorkflowController workflowController = GetWorkflowController();
                if (workflowController != null)
                {
                    ActivityLink activityLink = workflowController.GetActivityLink();
                    if (activityLink != null)
                    {
                        ActivityLinkNode foundNode = activityLink.FindNode(activeActivityName);
                        if (foundNode != null)
                        {
                            ActivityLinkNode current = foundNode.LastChild;
                            if (current != null && current.Value.IndexOf("Post") == -1)
                            {
                                if (current != null && current.Value != ActivityNameConsts.PostSubmission)
                                {
                                    do
                                    {
                                        if (current.Value.IndexOf("Post") == -1 && current.Value != ActivityNameConsts.End)
                                        {
                                            if (_activeActivityName.IndexOf(EZVisitActivityNameConsts.COD_PP_Check_Person) > -1 && current.Value == EZVisitActivityNameConsts.PDC)
                                            {
                                                current = current.LastChild;
                                            }
                                            else
                                            {
                                                    DataRow row = done.NewRow();
                                                    row["ProcessStampID"] = Guid.NewGuid();
                                                    row["ProcName"] = GetProcName();
                                                    row["ActivityName"] = current.Value;
                                                    row["Status"] = 0;
                                                    row["StampType"] = K2StampType.Tobe;
                                                    done.Rows.Add(row);
                                                current = current.LastChild;
                                            }
                                        }
                                        else
                                        {
                                            current = current.LastChild;
                                        }
                                    } while (current != null && current.Value != ActivityNameConsts.PostSubmission);
                                }
                            }
                        }
                    }
                }
            }

            done.AcceptChanges();
            return done;
        }

        public virtual DataTable GetDataSourcePostEZVisit(int appFormId, int procInstId)
        {
            DataTable done = K2DataHelper.GetProcessStampPostEZVisit(procInstId);

            foreach (DataRow row in done.Rows)
            {
                row["StampType"] = K2StampType.Done;
            }

            MyActivityTableEntitySet active = K2DataHelper.GetMyActivities(procInstId, new int[] { (int)MyActivityStatus.Normal });

            string activeActivityName = string.Empty;
            string targetActivityName = string.Empty;
            if (active != null)
            {
                foreach (MyActivityTableEntity entity in active)
                {
                    if (string.IsNullOrEmpty(activeActivityName))
                    {
                        activeActivityName = entity.K2ActivityName;
                        _activeActivityName = activeActivityName;
                    }
                    else
                    {
                        activeActivityName = entity.K2ActivityName;
                        string tempActivity = ";" + _activeActivityName;
                        if (tempActivity.IndexOf(";" + activeActivityName) == -1)
                            _activeActivityName += ";" + activeActivityName;
                    }

                    if (entity.SourceActionType == K2ActionType.AskForMore)
                    {
                        if (string.IsNullOrEmpty(targetActivityName))
                        {
                            targetActivityName = entity.TargetActivityName;
                        }
                    }

                    if (entity.K2ActivityName.IndexOf("Post") > -1)
                    {
                        DataRow row = done.NewRow();
                        row["ProcessStampID"] = Guid.NewGuid();
                        row["ProcName"] = GetProcName();
                        row["ActivityName"] = entity.K2ActivityName;
                        row["ActionType"] = string.Empty;
                        row["OwnerID"] = entity.OwnerID ?? 0;
                        row["OwnerEn"] = entity.OwnerEn;
                        row["OwnerCn"] = entity.OwnerCn;
                        row["DelegateFromID"] = entity.DelegateFromID ?? 0;
                        row["DelegateFromEn"] = entity.DelegateFromEn;
                        row["DelegateFromCn"] = entity.DelegateFromCn;
                        row["ApplicationNo"] = entity.ApplicationNo;
                        row["ProcInstID"] = entity.K2ProcInstID ?? 0;
                        row["CreatedDate"] = entity.CreatedDate;
                        row["Status"] = 0;
                        //row["ActionRecordID"] = ;
                        row["StampType"] = K2StampType.Active;
                        done.Rows.Add(row);
                    }
                }
            }

            if (!string.IsNullOrEmpty(targetActivityName))
            {
                _activeActivityName = activeActivityName + " asked for more";
            }

            if (!string.IsNullOrEmpty(activeActivityName))
            {
                IWorkflowController workflowController = GetWorkflowController();
                if (workflowController != null)
                {
                    ActivityLink activityLink = workflowController.GetActivityLink();
                    if (activityLink != null)
                    {
                        ActivityLinkNode foundNode = activityLink.FindNode(activeActivityName);
                        if (foundNode != null)
                        {
                            ActivityLinkNode current = foundNode.LastChild;

                            if (current != null && current.Value != ActivityNameConsts.End)
                            {
                                do
                                {
                                    if (current.Value.IndexOf("Post") > -1)
                                    {
                                        DataRow row = done.NewRow();
                                        row["ProcessStampID"] = Guid.NewGuid();
                                        row["ProcName"] = GetProcName();
                                        row["ActivityName"] = current.Value;
                                        row["Status"] = 0;
                                        row["StampType"] = K2StampType.Tobe;
                                        done.Rows.Add(row);
                                    }
                                    current = current.LastChild;

                                } while (current != null && current.Value != ActivityNameConsts.End);
                            }
                        }
                    }
                }
            }

            done.AcceptChanges();
            return done;
        }

        #endregion

        #region IWorkflowControl Members

        public void BindData(int appFormId, int procInstId)
        {
            HtmlGenericControl divStampControl = GetStampControl();
            if (divStampControl != null)
            {
                IWorkflowPage workflowPage = Page as IWorkflowPage;
                string processStatus = workflowPage.GetAppForm().ProcessStatus;
                if (string.IsNullOrEmpty(processStatus) || processStatus == ProcessStatusConsts.Draft || processStatus == ProcessStatusConsts.Discarded)
                {
                    divStampControl.Style["display"] = "none";
                    return;
                }
            }

            DataList dlStamp = GetStampDataListEZVisit();
            if (dlStamp == null) return;
            dlStamp.DataSource = GetDataSourceEZVisit(appFormId, procInstId);
            dlStamp.DataBind();
            DataList dlStampPost = GetStampDataListPostEZVisit();
            if (dlStampPost == null) return;
            dlStampPost.DataSource = GetDataSourcePostEZVisit(appFormId, procInstId);
            dlStampPost.DataBind();

            BindControls();
        }

        #endregion
    }
}
